package com.wisezone.java1902.d13_sort1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class TestUser {

	public static void main(String[] args) {
		User user1 = new User("小明",22);
		User user2 = new User("小丽",23);
		User user3 = new User("张三",21);
		User user4 = new User("李四",20);

		List<User> userLists = new ArrayList<>(); //动态数组容器
		userLists.add(user1);
		userLists.add(user2);
		userLists.add(user3);
		userLists.add(user4);
		
		//遍历容器  for  for-each  iterator
		
		//普通for循环
//		int size = userLists.size();
//		for (int i = 0; i < size; i++) {
//			User user = userLists.get(i);
//			System.out.println(user);
//		}
		
		//for-each
//		for(User user : userLists) {
//			System.out.println(user);
//		}
		
		//迭代器
		Iterator<User> iterator = userLists.iterator();
		while(iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		
        //排序
		Collections.sort(userLists, new Comparator<User>() {

			@Override
			public int compare(User o1, User o2) {
//				int age = o1.getAge() - o2.getAge();
				if(o1.getAge() > o2.getAge()) {
					return 1; //返回正数, o2排o1前面
				}else if(o1.getAge() < o2.getAge()) {
					return -1; //返回负数，o1排o2前面
				}else {
					return 0; //返回0按照原来规则排序
				}
			}
			
		});
		
		System.out.println("排序之后");
		
		for (User user : userLists) {
			System.out.println(user);
		}
		
	}

}
